package com.atguigu.gulimall.order.interceptor;

import com.atguigu.common.constant.SessionAttrKeyConstant;
import com.atguigu.common.vo.MemberEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberEntity> loginUser = new ThreadLocal<>();

    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        // 出现问题 : 远程调用订单服务时被拦截器拦截
        // 解决方案 : 请求路径适配放行
        String uri = request.getRequestURI();
        boolean match = new AntPathMatcher().match("/order/order/status/**", uri);
        if(match){
            return true;
        }

        MemberEntity memberEntity = (MemberEntity)request.getSession().getAttribute(SessionAttrKeyConstant.LOGIN_USER);
        if(memberEntity != null){
            // 登录成功后,将用户信息存储至ThreadLocal中方便其他服务获取用户信息
            loginUser.set(memberEntity);
            return true;
        }else{
            // 未登录请先登录
            request.getSession().setAttribute("msg","请先进行登录");
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }
    }
}
